package com.codeplex.jtfscli.commands;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import com.codeplex.jtfscli.util.ArgParser;
import com.codeplex.jtfscli.util.TFSConnectionFactory;

public abstract class Command {
	protected final TFSConnectionFactory connectionFactory;

	public Command(final TFSConnectionFactory connectionFactory) {
		this.connectionFactory = connectionFactory;
	}

	public Command() {
		this(new TFSConnectionFactory());
	}

	public void run(final String[] args) throws Exception {
		final BufferedReader br = new BufferedReader(new InputStreamReader(
				System.in));
		final Map<String, String> parsedArgs = ArgParser.parse(Arrays
				.asList(args));
		final String username, password;
		if (parsedArgs.containsKey("-login")) {
			final String login = parsedArgs.get("-login");
			final int commaIndex = login.indexOf(',');
			username = login.substring(0, commaIndex);
			password = login.substring(commaIndex + 1);
		} else {
			System.out.print("username: ");
			username = br.readLine();
			System.out.print("password: ");
			password = br.readLine();
		}
		this.run(args, username, password);
	}

	public void run(final String[] args, final String usernameAndDomain,
			final String password) throws Exception {
		run(ArgParser.parse(Arrays.asList(args)),
				ArgParser.findRegularArgs(Arrays.asList(args).subList(1,
						args.length)), usernameAndDomain, password);
	}

	/**
	 * 
	 * @param parsedArgs
	 *            Mapping of argument name -> argument value.
	 * @param regularArgs
	 *            Any arguments without a flag. Does not contain the first
	 *            argument (the one that is, for example, 'get', 'workspaces',
	 *            etc.)
	 * @param usernameAndDomain
	 * @param password
	 * @throws Exception
	 */
	public abstract void run(final Map<String, String> parsedArgs,
			final List<String> regularArgs, final String usernameAndDomain,
			final String password) throws Exception;
}
